package com.example.forum.services.impl;
import cn.hutool.core.util.RandomUtil;
import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.UserMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.utils.MD5Util;
import com.example.forum.utils.StringUtil;
import com.example.forum.utils.UUIDUtil;
import com.zbu.common.core.constants.Constants;
import com.zbu.common.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    RedisService redisService;
    @Resource
    UserMapper userMapper;
    @Value("${sendCode.email}")
    private String sendCodeEmail;
    @Value("${sendCode.title}")
    private String sendCodeName;
    @Value("${sendCode.password}")
    private String sendCodePassword;//授权码
    @Value("${sendCode.title}")
    private String sendCOdeTitle;
    @Value("${sendCode.number}")
    private Integer sendCodeNumber;//发送验证码的位数
    @Value("${sendCode.management}")
    private String sendCodeManagement;
    @Value("${sendCode.hostname}")
    private String sendCodeHostName;
    @Value("${sendCode.limit}")
    private Long sendCodeLimit;
    @Override
    public User seleceByUserName(String username) {
        if(StringUtil.isEmpty(username)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return userMapper.selectByUserName(username);
    }

    @Override
    public void createNormalUser(User user) {
        if (user == null || StringUtil.isEmpty(user.getUsername())
                || StringUtil.isEmpty(user.getNickname()) || StringUtil.isEmpty(user.getPassword())
                || StringUtil.isEmpty(user.getSalt())) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常， 统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 2. 按用户名查询用户信息
        User existsUser = userMapper.selectByUserName(user.getUsername());
        // 2.1 判断用户是否存在
        if (existsUser != null) {
            // 打印日志
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }

        // 3. 新增用户流程,设备默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        // 当前日期
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        // 写入数据库
        int row = userMapper.insertSelective(user);
        if (row != 1) {
            // 打印日志
            log.info(ResultCode.FAILED_CREATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        // 打印日志
        log.info("新用户成功. username = " + user.getUsername() + ". ");
    }

    @Override
    public User login(String username, String password) {
        //非空检验
        if(StringUtil.isEmpty(username)||StringUtil.isEmpty(password)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //按照用户名查询用户信息
        User user=seleceByUserName(username);
        //对查询结果进行非空判断
        if(user==null){
            log.warn(ResultCode.FAILED_LOGIN.toString()+",username="+username);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //对查询到的用户密码与输入的用户密码进行校验
        String encryptPassword= MD5Util.md5Salt(password,user.getSalt());
        //用密文和数据库中保存的密码进行比较查看是否相同
        if(!encryptPassword.equalsIgnoreCase(user.getPassword())){
            //打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString()+"密码错误");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //经过以上判断后说明登录成功
        log.info("登录成功,username=",username);
        //返回用户信息即可
        return user;
    }

    /**
     * 对接口中通过用户Id查找用户方法的实现
     * @param id 前端传入的用户ID
     * @return
     */
    @Override
    public User selectById(Long id) {
        if(id==null){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user=userMapper.selectByPrimaryKey(id);
        return user;
    }

    /**
     * 根据用户ID将用户发帖数减1
     * @param id 要更新的对象
     */

    @Override
    public void subOneArticleCountById(Long id) {
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        // 查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            // 打印日志
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ", user id = " + id);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        // 更新用户的发帖数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() - 1);
        // 判断减1之后，用户的发帖数是否小于0
        if (updateUser.getArticleCount() < 0) {
            // 如果小于0，则设置为0
            updateUser.setArticleCount(0);
        }

        // 更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if(id==null||id<=0){
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            //抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        //查询用户信息
        User user=userMapper.selectByPrimaryKey(id);
        if(user==null){
            //打印日志
            log.warn(ResultCode.ERROR_IS_NULL.toString()+"user id:"+id);
            throw  new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //更新用户的发帖数量
        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()+1);
        //更新数据库
        int row =userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }

    }

    @Override
    public void modifyInfo(User user) {
        //参数校验
        if(user==null||user.getId()==null||user.getId()<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //检验用户是否存在
        User existsUser=userMapper.selectByPrimaryKey(user.getId());
        if(existsUser==null){
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //检验输入的各个参数使用一个变量进行校验
        boolean checkAttr=false;
        // 4. 定义一个专门用来更新的对象，防止用户传入的User对象设置了其他的属性
        // 当使用动态SQL进行更新的时候，覆盖了没有经过校验的字段
        User updateUser = new User();
        updateUser.setId(user.getId());
        if(!StringUtil.isEmpty(user.getUsername())&&!existsUser.getUsername().equals(user.getUsername())){
            //对用户名进行唯一性判断
            User checkUser=userMapper.selectByUserName(user.getUsername());
            if(checkUser!=null){
                //打印日志
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                //抛出异常
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }
            updateUser.setUsername(user.getUsername());
            checkAttr=true;
        }
        // 校验昵称
        if(!StringUtil.isEmpty(user.getNickname())&&!existsUser.getNickname().equals(user.getNickname())){
            updateUser.setNickname(user.getNickname());
            checkAttr=true;
        }
        //校验性别
        if(user.getGender()!=null&&existsUser.getGender()!=user.getGender()){
            updateUser.setGender(user.getGender());
            // 合法性校验
            if (updateUser.getGender() > 2 || updateUser.getGender() < 0) {
                updateUser.setGender((byte) 2);
            }
            checkAttr=true;
        }
        //校验邮箱
        if(!StringUtil.isEmpty(user.getEmail())&&!existsUser.getEmail().equals(user.getEmail())){
            updateUser.setEmail(user.getEmail());
            checkAttr=true;
        }
        //校验电话号码
        if(!StringUtil.isEmpty(user.getPhoneNum())&&!existsUser.getPhoneNum().equals(user.getPhoneNum())){
            updateUser.setPhoneNum(user.getPhoneNum());
            checkAttr=true;
        }
        //校验个人简介
        if(!StringUtil.isEmpty(user.getRemark())){
            updateUser.setRemark(user.getRemark());
            checkAttr=true;
        }
        //根据标志位来决定是否可以执行更新
        if(checkAttr==false){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用Dao
        int row=userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyPassword(Long id, String oldPassword, String newPassword) {
        //非空校验
        if(id==null||id<=0||StringUtil.isEmpty(newPassword)
           ||StringUtil.isEmpty(oldPassword)){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询用户信息
        User user=userMapper.selectByPrimaryKey(id);
        //检验用户是否存在
        if(user==null){
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //检验老密码是否正确
        //对老密码进行加密获取密文
        String oldEncryptPassword=MD5Util.md5Salt(oldPassword,user.getSalt());
        //与用户当前密码进行比较
        if(!oldEncryptPassword.equalsIgnoreCase(user.getPassword())){
            System.out.println(oldEncryptPassword);
            System.out.println(user.getPassword());
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 生成一个新的盐值
        String salt = UUIDUtil.UUID_32();
        // 生成新密码的密文
        String encryptPassword = MD5Util.md5Salt(newPassword, salt);
        //生成一个新的对象
        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setSalt(salt);
        updateUser.setPassword(encryptPassword);
        Date date=new Date();
        updateUser.setUpdateTime(date);
        //调用Dao
        int row =userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1) {
            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    /**
     * 验证码生成
     * @return
     */

    public  String Random_number(){
        // 种子数都设为6
        Random numList = new Random();
        StringBuilder random=new StringBuilder();
// 随机生成4个随机数并且将其拼接为字符串
        for(int i=0; i<4; i++) {
            //生成一个[0,10)之间的随机数
            int num =  numList.nextInt(10) ;
            random.append(String.valueOf(num));
        }
        return new String(random);
    }

    /**
     * 发送邮件验证码
     * @param email 电子邮箱
     * @return
     * @throws EmailException
     */
    @Override
    public boolean sendverify(String email)  {
        String random=RandomUtil.randomNumbers(sendCodeNumber);
        try {
            HtmlEmail htmlEmail=getHtmlEmail(email,random);
            htmlEmail.send();//进行发送
        }catch (EmailException e){
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_SEND_CODE));
        }
        addEmailCodeToRedis(email,random);
        return true;
    }
    public HtmlEmail getHtmlEmail(String email,String random) throws EmailException {
        HtmlEmail htmlEmail=new HtmlEmail();
        htmlEmail.setHostName(sendCodeHostName);
        htmlEmail.setSSLOnConnect(true);
        htmlEmail.setCharset("utf-8");//设置发送的字符类型
        htmlEmail.addTo(email);//设置目标邮箱
        htmlEmail.setFrom(sendCodeEmail,sendCodeName);
        htmlEmail.setAuthentication(sendCodeEmail,sendCodePassword);//设置发送人到的邮箱和用户名和授权码(授权码是自己设置的)
        htmlEmail.setSubject(sendCOdeTitle);//设置发送主题
        htmlEmail.setMsg(sendCodeManagement+random);//设置发送内容
        return htmlEmail;
    }
    private static String getUserEmailKey(String email) {
        return Constants.CODE_KEY + email;
    }

    @Override
    public boolean judgmentverification_code(String email, String verification_code) {
        if(StringUtil.isEmpty(email)||StringUtil.isEmpty(verification_code)){
            //写日志
            log.warn("邮箱和验证码为空");
            throw new ApplicationException(AppResult.failed("邮箱或验证码为空"));
        }
        String emailKey= getUserEmailKey(email);
        String emailCode=redisService.getCacheObject(emailKey,String.class);
        if(emailCode==null||!emailCode.equals(verification_code)){
            return false;
        }
        return true;
    }

    /**
     * 删除验证码
     * @param email
     */
    public void deleteMap(String email){
        String emailKey=getUserEmailKey(email);
        if(!redisService.deleteObject(emailKey)){
            //写日志
            log.warn("不包含这组邮箱");
            throw new ApplicationException(AppResult.failed("不包含这组邮箱"));
        }
    }

    /**
     * 向redis中添加键值对即发送的验证码并设置过期时间
     * @param email
     * @param random
     */
    public void addEmailCodeToRedis(String email, String random){
        String userEmailKey=getUserEmailKey(email);
        redisService.setCacheObject(userEmailKey,random,sendCodeLimit, TimeUnit.MINUTES);
    }

}
